package com.yuda.tools.log.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyun.oss.model.SimplifiedObjectMeta;
import com.yuda.tools.log.config.LogConstant;
import com.yuda.tools.log.entity.OssBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class OssUtil {
	
	static Logger logger = LoggerFactory.getLogger(OssBean.class);

	/**
	 * 真正调用的上传的方法
	 * @param ossBean
	 */
    public static void uploadFile(OssBean ossBean) {
    	
    	 String buckName = ossBean.getBucketName();
    	 String endPoint = ossBean.getOssEndPoint();
    	 String accessKey = ossBean.getAccessKey();
    	 String accessSecret = ossBean.getAccessSecret();
    	 String key = ossBean.getKey();
    	 String uploadFile = ossBean.getUploadFilePath();
    	 
	     OSSClient client = new OSSClient(endPoint, accessKey,accessSecret);
	     try {
	    	 File file = null;
		     if(key != null) {
		    	 file = new File(uploadFile);
		     }
	          if( null != file && file.exists()) {
	        	  //client.deleteObject(buckName, key);  
	        	  upload(client, ossBean.getBucketName(), ossBean.getKey(),ossBean.getUploadFilePath());
	          }
		} catch (OSSException | ClientException | FileNotFoundException e) {
			e.printStackTrace();
		} finally{
			if(null != client) {
				client.shutdown();
			}
		}
    }
    
    /**
     * 真正调用的下载的方法
     * @param ossBean
     */
    public static int downLoadFile(OssBean ossBean) {
    	OSSClient client = null;
		try {
			client = new OSSClient(ossBean.getOssEndPoint(), ossBean.getAccessKey(), ossBean.getAccessSecret());
			if(client.doesObjectExist(ossBean.getBucketName(), ossBean.getKey())){//如果文件存在在下载
				//logger.info("正在下载..."+ossBean.getKey());  
		       // long startTime_d = System.currentTimeMillis();  
				download(client, ossBean.getBucketName(), ossBean.getKey(), ossBean.getDownloadFilePath());
				//long endTime_d = System.currentTimeMillis();  
				//logger.info("下载花费时间约：" + (endTime_d - startTime_d) + " ms");  
				return 1;
			}else{
				//logger.error(ossBean.getKey()+"下载失败不存在");
				return 0;
			}
		} catch (Throwable e) {
			//logger.error("下载失败，抛出异常");
			return -1;
		} finally{
    		if(null != client) {
    			client.shutdown();
    		}
		}
    }
    
    /**
     * 循环所有bucketName找出存入时间最新的Log文件
     * @param ossBean
     * @param xiTong 
     */
    public static OssBean changeBucketName(OssBean ossBean, String xiTong) {
    	Map<String,OssBean> MapOss = new HashMap<>();
    	List<Integer> stime = new ArrayList<>();
    	for(String[] strings: LogConstant.OSSINFO) {
    		OssBean newOss = new OssBean();
    		newOss.setAccessKey(ossBean.getAccessKey());
    		newOss.setAccessSecret(ossBean.getAccessSecret());
    		newOss.setDownloadFilePath(ossBean.getDownloadFilePath());
    		newOss.setBucketName(strings[0]);
    		newOss.setKey(ossBean.getKey());
			if(xiTong.toUpperCase().startsWith("WIN") ) {
				newOss.setOssEndPoint(strings[2]);////内网 paper_inner_endpoint    外网paper_out_endpoint  TODO
			}else {
				newOss.setOssEndPoint(strings[1]);//如果是linux系统用内网
			}
			
    		OSSClient client = new OSSClient(newOss.getOssEndPoint(), newOss.getAccessKey(), newOss.getAccessSecret());
    		if(client.doesObjectExist(newOss.getBucketName(), newOss.getKey())){//如果文件存在
    			SimplifiedObjectMeta objectMeta = client.getSimplifiedObjectMeta(newOss.getBucketName(), newOss.getKey());
        		String timeStr = DateUtil.changeDateFormat(objectMeta.getLastModified());
        		int intTime = StringToInteger(timeStr);
        		logger.info(newOss.getBucketName()+"=====>"+timeStr +" "+newOss.getKey());
        		logger.info(newOss.getBucketName()+"插入oss的时间=====>"+intTime);
        		MapOss.put(intTime+"str", newOss);
        		stime.add(intTime);
    		}
    	}
    	
    	//判断最新时间的Log日志
    	int maxS=0;
    	for(int s:stime) {
    		 if(s>maxS) {
    			 maxS=s;
    			 
    		 }
    	}
    	if(maxS != 0) {
    		OssBean vel = MapOss.get(maxS+"str");
    		return vel;
    	}else {
    		return null;
    	}
    	
    	/*Iterator<Entry<Integer, OssBean>> it = MapOss.entrySet().iterator();
    	 while (it.hasNext()) {
    	     Entry<Integer, OssBean> entry = it.next();
    	     //System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
    	    if(entry.getKey() == maxS) {
    	    	return entry.getValue();
    	    }
    	 }*/
		
    }
    
    private static int StringToInteger(String key) {
    	String new1 = key.replaceAll(":", "");
    	new1 = new1.replaceAll("-", "");
    	new1 = new1.substring(4);
    	int a1 = Integer.parseInt(new1);
		return a1;
	}

	public static boolean isExist(OssBean ossBean) {
    	OSSClient client = null;
    	try {
    		client = new OSSClient(ossBean.getOssEndPoint(), ossBean.getAccessKey(), ossBean.getAccessSecret());
    		if(client.doesObjectExist(ossBean.getBucketName(), ossBean.getKey())){//如果文件存在在下载
    			return true;
    		}else{
    			return false;
    		}
    	} catch (Throwable e) {
    		return true;
    	} finally{
    		if(null != client) {
    			client.shutdown();
    		}
    	}
    }
    
  
    // 上传文件  的具体方法
    private static void upload(OSSClient client, String bucketName,
                               String key, String filename) throws OSSException, ClientException,
            FileNotFoundException {
        File file = new File(filename);
  
        ObjectMetadata objectMeta = new ObjectMetadata();
        objectMeta.setContentLength(file.length());  
  
        InputStream input = new FileInputStream(file);
        PutObjectResult rs = client.putObject(bucketName, key, input,objectMeta);
        logger.info("上传成功：" + rs.getETag());  
    }  
  
    // 下载文件  具体方法
    private static void download(OSSClient client, String bucketName,
                                 String key, String filename) throws Throwable {
        try {
			client.getObject(new GetObjectRequest(bucketName, key), new File(filename));
			//logger.info("下载成功");
		} finally {
			if (client != null) {
				client.shutdown();
			}
		}  
     // 下载请求，10个任务并发下载，启动断点续传   
//     DownloadFileRequest downloadFileRequest = new DownloadFileRequest(bucketName, key); 
//     downloadFileRequest.setDownloadFile(filename);
//     downloadFileRequest.setTaskNum(10);
//     downloadFileRequest.setEnableCheckpoint(true);
//     // 下载文件
//     DownloadFileResult downloadRes = client.downloadFile(downloadFileRequest);
//     // 下载成功时，会返回文件的元信息
//     downloadRes.getObjectMetadata();
     // 关闭client
     
    }  
}
